package com.tanhua.admin.service;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.admin.mapper.AnalysisMapper;
import com.tanhua.admin.mapper.LogMapper;
import com.tanhua.model.domain.Analysis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class AnalysisService {
    @Autowired
    private AnalysisMapper analysisMapper; //统计表

    @Autowired
    private LogMapper logMapper; //日志表

    //计算日志表中数据，保存或更新到统计表
    public void analysis() throws ParseException {
        //0. 获取今天和昨天日期
        String today = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String yesterday = DateUtil.yesterday().toString("yyyy-MM-dd");
        //1、查询数据
        //1.1 新注册用户数
        Integer numRegistered = logMapper.queryByLogTimeAndType("0102", today);
        //1.2 活跃用户数
        Integer numActive = logMapper.queryLogTime(today);
        //1.3 登陆人数
        Integer numLogin = logMapper.queryByLogTimeAndType("0101", today);
        //1.4 次日留存用户数
        Integer numRetention1d = logMapper.queryNumRetention1d(today, yesterday);
        //2、根据统计日志查询数据
        QueryWrapper<Analysis> qw = new QueryWrapper<>();
        qw.eq("record_date", today);
        Analysis analysis = analysisMapper.selectOne(qw);
        //3、判断数据是否存在
        if (analysis == null) {
            //3.1 数据不存在，保存
            analysis = new Analysis();
            analysis.setNumActive(numActive);
            analysis.setNumLogin(numLogin);
            analysis.setNumRegistered(numRegistered);
            analysis.setNumRetention1d(numRetention1d);
            analysis.setCreated(new Date());
            analysis.setRecordDate(new SimpleDateFormat("yyyy-MM-dd").parse(today));//日期
            analysisMapper.insert(analysis);
        } else {
            //3.2 数据存在，更新
            analysis.setNumLogin(numLogin);
            analysis.setNumActive(numActive);
            analysis.setNumRegistered(numRegistered);
            analysis.setNumRetention1d(numRetention1d);
            analysisMapper.updateById(analysis);
        }

    }
}
